import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { map } from 'rxjs/operators';
import { EntityPageResult } from 'src/app/model/entity-page-result';
import { LetterDigestVo } from 'src/app/model/letter-digest-vo';
import { MemberVo } from 'src/app/model/member-vo';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { LetterService } from 'src/app/services/letter.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { UtilService } from 'src/app/services/util.service';
import { HttpErrorResponse } from '@angular/common/http';
import { MemberService } from 'src/app/services/member.service';

@Component({
  selector: 'app-inbox-chat-page',
  templateUrl: './inbox-chat-page.component.html',
  styles: [``]
})
export class InboxChatPageComponent implements OnInit {
  public errorMessage: string = '';
  public curMember: MemberVo | null;
  //当前页码值
  public page: number = 1;
  //每页显示的数量
  public pageSize: number = 5;
  public items: LetterDigestVo[] = [];
  public hasNext: boolean = false;
  //当前的URL,用以浏览历史:window.history.pushState
  private url: string = '#';
  private sender: number = -1;
  private sendNickname!: string;
  private robot:boolean = false;
  public form:any = {
    content: '',
    receiver: -1 
  };
  /**
   * 收件箱中的消息内容
   * @param title 
   * @param location 
   * @param router 
   * @param activatedRoute 
   * @param letterService 
   * @param memberService 
   * @param memberStorage 
   * @param util 
   * @param btnNaviSharedService 
   */
  constructor(
    private title: Title,
    private location: Location,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private letterService: LetterService,
    private memberService: MemberService,
    private memberStorage: MemberStorageService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
      this.btnNaviSharedService.active(false);//不需要全局的导航
      this.curMember = this.memberStorage.get();
      this.activatedRoute.url.pipe(map(s => s.join('/'))).subscribe(res => {
        this.url = '/' + res;
      });
  }

  ngOnInit(): void {
    if(null === this.curMember) {
      this.router.navigate(['/member/login']);
    }
    this.sender = parseInt(this.activatedRoute.snapshot.paramMap.get('sender') ?? '-1');
    this.memberService.get(this.sender).subscribe({
      next: response => {
        this.sendNickname = response.nickname;
      },
      error: err => {
        this.sendNickname = (0>=this.sender)?'机器人':'@u'+this.sender;
      },
      complete: () => { console.log('[Inbox-Page]query sender Completed'); }
    });
    //
    this.robot = this.sender <= 0;
    this.form.receiver = this.sender;
    //
    this.page = +(this.activatedRoute.snapshot.queryParamMap.get('p') ?? 1);
    this.pageSize = +(this.activatedRoute.snapshot.queryParamMap.get('s') ?? 5);
    this.getDate();
  }

  //加载指定页码的数据
  private getDate(): void {
    this.letterService.getMessageChat(this.sender, this.curMember?.id ?? 0, this.page, this.pageSize).subscribe({
      next: response => {
        const rs:EntityPageResult<LetterDigestVo> = response as EntityPageResult<LetterDigestVo>;
        let curData: LetterDigestVo[] = rs.result.sort((ldv1:LetterDigestVo, ldv2:LetterDigestVo)=>{ 
          if (ldv1.id > ldv2.id) { return 1; }  
          if (ldv1.id < ldv2.id) {return -1; }  
          return 0;  
        });
        //计算结果
        this.items = curData.concat(this.items);
        this.hasNext = rs.total > rs.page * rs.size;
      },
      error: err => {
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            this.errorMessage = err.error.message;
          } else {
            this.errorMessage = err.error;
          }
        } else if (err instanceof Error) {
          this.errorMessage = err.message;
        } else { this.errorMessage = err; }
        console.log('[Inbox-Page]view error ' + this.errorMessage);
      },
      complete: () => { console.log('[Inbox-Page]view Completed'); }
    });
  }

  //底部的点击加载更多,后期会替换为:自动加载
  public anymore(event: Event): void {
    this.page += 1;
    this.getDate();
    this.location.replaceState(this.url, 'p=' + this.page + '&s=' + this.pageSize);
  }

  //标记为已读
  //:/message/read/all?member=${sender}&direction=1
  public readed(sender:number): void{
    this.letterService.readAll(this.curMember?.id??0, 1, sender).subscribe({
      next: response => {
        this.util.alertSuccess('标记成功');
      },
      error: err => {
        let em: string = '';
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            em = err.error.message;
          } else {
            em = (err.status === 417) ? '操作失败' : err.error;
          }
        } else if (err instanceof Error) {
          em = err.message;
        } else { em = err; }
        this.util.alertError(em);
        console.log('[Inbox-Chat]readed error ' + em);
      },
      complete: () => { console.log('[Inbox-Chat]readed Completed'); }
    });
  }

  //发送消息
  public sendMessage():void {
    this.letterService.send(this.curMember?.id??0, this.curMember?.nickname??'guest', null, this.form.content, this.form.receiver).subscribe({
      next: response => {
        this.items.push(response);
        this.form.content = '';
      },
      error: err => {
        let em: string = '';
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            em = err.error.message;
          } else {
            em = (err.status === 404) ? '发送失败' : err.error;
          }
        } else if (err instanceof Error) {
          em = err.message;
        } else { em = err; }
        this.util.alertError(em);
        console.log('[Inbox-Chat]sent error ' + em);
      },
      complete: () => { console.log('[Inbox-Chat]sent Completed'); }
    });
  }
}
